import axios from "axios";
import router from "./router";
import Element from "element-ui"
import JSEncrypt from 'jsencrypt/bin/jsencrypt'
import CryptoJS from 'crypto-js'
import store from './store'
import keys from './util/keys'

process.env.NODE_ENV == 'development' ? axios.defaults.baseURL = "/api" : axios.defaults.baseURL = "/"
// axios.defaults.baseURL = "/" //线上
// axios.defaults.baseURL = "/api" //本地

const request = axios.create({
	timeout: 5000,
	withCredentials: true,
	headers: {
		'Content-Type': "application/json; charset=utf-8"
	}
})

let Encrypt = new JSEncrypt()
let publicKey = keys.publicKey
let privateKey = keys.privateKey

request.interceptors.request.use(config => {
	store.commit('SET_Loading',true)
	// config.headers['Authorization'] = localStorage.getItem("token")
	
	// Encrypt.setPublicKey(publicKey)
	// // Encrypt.setPrivateKey(privateKey)
	// if(!config.data) config.data = {}
	// config.data.timeStamp = Date.now() / 1000
	// console.log('111',JSON.stringify(config.data));
	// let word = Encrypt.encrypt(JSON.stringify(config.data))
	// console.log(word);
	// Encrypt.setPrivateKey(privateKey)
	// let signature = Encrypt.sign(JSON.stringify(config.data), CryptoJS.SHA1, "sha1")
	// config.data = {
	// 	content: word,
	// 	sign:signature
	// }
	return config
})

request.interceptors.response.use(
	response => {
		// Encrypt.setPrivateKey(privateKey)
		// Encrypt.setPublicKey(publicKey)
		// response.data = JSON.parse(Encrypt.decrypt(response.data))

		// Encrypt.setPublicKey(publicKey)
		// Encrypt.setPrivateKey(privateKey)
		// let word = Encrypt.encrypt('33jio得')
		// // console.log(word);
		// // word = Base64.encode(word)
		// // word = Base64.decode(word)
		// console.log(word);
		// word = Encrypt.decrypt(word)
		// console.log(word);
		let res = response.data
		store.commit('SET_Loading',false)
		if (res.status === 1) {
			return response
		} else {
			Element.Message.error(!res.msg ? '系统异常' : res.msg)
			return Promise.reject(response.data.msg)
		}
	},
	error => {
		if (error.response.status === 401) {
			Element.Message.error('登录失效，请重新登录')
			router.push("/login")
			return
		}

		Element.Message.error(error.response.data.message || '请求错误', {
			duration: 3000
		})
		store.commit('SET_Loading',true)
		return Promise.reject(error)
	}
)

export default request